<?php

namespace app\admin\controller\cooperate;

use app\common\controller\Backend;
use app\common\library\Auth;
use app\common\library\FlowEngine;
use fast\Tree;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use app\common\constant;
use think\Log;

/**
 * 合作
 *
 * @icon fa fa-circle-o
 */
class Cooperation extends Backend
{
    /**
     * Apply模型对象
     * @var
     */
    protected $cooperation = null;
    protected $number = null;
    protected $instance = null;
    protected $task = null;
    protected $scheme = null;
    protected $flow = null;
    protected $adminModel = null;

    /**
     * 快速搜索时执行查找的字段
     */
    protected $searchFields = '';

    /**
     * 是否是关联查询
     */
    protected $relationSearch = true;

    public function _initialize()
    {
        parent::_initialize();
        $this->cooperation = new \app\admin\model\flow\Cooperation();
        $this->number = new \app\admin\model\flow\Number();
        $this->instance = new \app\admin\model\flow\Instance();
        $this->task = new \app\admin\model\flow\Task();
        $this->scheme = new \app\admin\model\flow\Scheme();
        $this->adminModel = new \app\admin\model\Admin();
        $this->departmentList = $this->cooperation->allDepartmentName();
        $this->view->assign("departmentList", $this->departmentList);
        $this->view->assign("typeList", $this->cooperation->getTypeList());
    }

    /**
     * 导入
     */
    public function import()
    {
        parent::import();
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            //处理申请状态已完成，协议状态为签约
            Db::name('flow_instance')
                ->alias('instance')
                ->join('flow_cooperation cooperation', 'instance.bizobjectid = cooperation.id')
                ->where(['instance.scheme' => 1,'instance.instancestatus'=>2,'cooperation.validstatus'=>'-1'])
                ->update(['cooperation.validstatus'=>1]);
                //->select();

            //echo Db::name('flow_instance')->getLastSql();exit;

            //获取当前时间
            $before_data = date('Y-m-d 0:0:0');

            //处理过期的协议状态
            Db::name('flow_cooperation')
                ->where('validstatus',1)
                ->where('enddate','<',$before_data)
                ->where('enddate','<>','0000-00-00')
                ->update(['validstatus'=>2]);
                //->select();

            //echo Db::name('flow_cooperation')->getLastSql();exit;

            //设置自己账号只能查看自己的
            $unitWhere = [];
            $uInfo = $this->auth->getUserInfo();
            if(!empty($uInfo['id']) && isset($uInfo['id'])){
                $unitWhere['originator'] = ['in', $uInfo['id']];
            }

            //如果是管理员账号可以查看所有的
            if(in_array($uInfo['id'],constant\Consts::$Super)
                or $uInfo['nickname']=='王姝'
                or $uInfo['nickname']=='刘霆' or   $uInfo['nickname']=='张大松') {
                $unitWhere = [];
            }
            else if(!empty($uInfo['id']) && isset($uInfo['id'])){
                $unitWhere['originator'] = ['in', $uInfo['id']];
            }

            /*$total = Db::name('view_flow_workitem')
                ->where($where)
                ->where($unitWhere)
                ->where(['schemeid' => 1])
                ->where('deletetime','null')
                ->order($sort, $order)
                ->order('createtime desc,status asc,completedtime desc')
                ->count();

            $list = Db::name('view_flow_workitem')
                ->where($where)
                ->where($unitWhere)
                ->where(['schemeid' => 1])
                ->where('deletetime','null')
                ->order('createtime desc,status asc,completedtime desc')
                ->limit($offset, $limit)
                ->select();*/

//            $total = Db::name('my_flow_workitem')
//                ->where($where)
//                ->where($unitWhere)
//                ->where(['schemeid' => 1])
//                //->where('deletetime','null')
//                //->order($sort, $order)
//                ->order('createtime desc,status asc,completedtime desc')
//                ->count();
//
//            $list = Db::name('my_flow_workitem')
//                ->where($where)
//                ->where($unitWhere)
//                ->where(['schemeid' => 1])
//                //->where('deletetime','null')
//                ->order('createtime desc,status asc,completedtime desc')
//                ->limit($offset, $limit)
//                ->select();

            $total = Db::name('flow_instance')
                ->alias('instance')
                ->join('admin admin', 'admin.id = instance.originator')
				->join('flow_cooperation cooperation', 'instance.bizobjectid = cooperation.id')
                ->where($where)
                ->where($unitWhere)
                ->where(['scheme' => 1])
                //->order($sort, $order)
                ->order('validstatus asc,instance.createtime desc ')
                ->count();

            $list = Db::name('flow_instance')
                ->alias('instance')
                ->join('admin admin', 'admin.id = instance.originator')
				->join('flow_cooperation cooperation', 'instance.bizobjectid = cooperation.id')
                ->field('cooperation.*,instance.*,admin.department_id')
                ->where($where)
                ->where($unitWhere)
                ->where(['scheme' => 1])
                ->order('validstatus asc,instance.createtime desc')
               // ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            foreach($list as &$item){
                //增加发起人
                $item['initiator_id'] = Db::name('admin')->where(['id' => $item['originator']])->value('nickname');;

                if($item['bizobjectid']){
                    $cooperation = Db::name('flow_cooperation')->where(['id' => $item['bizobjectid']])->find();
                    if(!empty($cooperation)){
                        //$item['cooperation_id'] = isset($cooperation['cooperation_id'])?$cooperation['cooperation_id']:0;
                        //$item['cname'] = isset($cooperation['cname'])?$cooperation['cname']:'';

                        //var_dump($item['initiator_id']);exit;

						//两个表都有originator，要区分
						$item['jiafang'] = isset($cooperation['jiafang'])?$cooperation['jiafang']:'';
                       // $item['partner'] = isset($cooperation['partner'])?$cooperation['partner']:'';
                        if($cooperation['department_id']){
                            $item['department_name'] = Db::name('flow_department')->where('id' , $cooperation['department_id'])->value('name');
                        }
                        //$item['startdate'] = $cooperation['startdate'];
						// $item['enddate'] = $cooperation['enddate'];
						$item['ctype'] = $cooperation['type'];
						
						$item['validstatus'] = $cooperation['validstatus'];
						
						
                        if($cooperation['startdate'] == '0000-00-00') {
                            $item['startdate'] = '';
                        }
                        if($item['completedtime'] == '1990-01-01 00:00:00') {
                            $item['completedtime'] = '';
                        }
                    }
                }
            }

            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }

        $adminList = Db::name('admin')->field('id,nickname')->select();
        $this->assignConfig('adminList', array_column($adminList, 'nickname', 'id'));
        $deptList = Db::name('department')->field('id,name')->select();
        $this->assignConfig('deptList', array_column($deptList, 'name', 'id'));

        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $ids = $this->request->request('ids');
        $bizobjectid =Db::name('view_flow_instance')->where(['scheme' => 1])->where(['id' => $ids])->value('bizobjectid');
        $row = Db::name('flow_cooperation')->where(['id' => $bizobjectid])->find();
        if(!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                //var_dump($params);exit;
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    //$result = $row->allowField(true)->save($params);
                    $result = Db::name('flow_cooperation')->where(['id' => $bizobjectid])->update($params);
                    Db::commit();
                }
                catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                }
                else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign('participatingList', build_select('row[participating_departments][]',$this->departmentList, $row['participating_departments'], ['class' => 'form-control selectpicker','multiple'=>'']));
        $this->view->assign('divisionsList', build_select('row[divisions][]',$this->departmentList, $row['divisions'], ['class' => 'form-control selectpicker','multiple'=>'','data-rule'=>'required']));
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 考核
     **/
    public function check($id='')
    {
        $ids = input()['ids'];  //id集合
        for($i=0;$i<count($ids);$i++){
            $year = date("Y");
            //查询合作信息
            //$info = Db::name('flow_instance')->where(['id' => $ids[$i]])->where('instancestatus',2)->find();
            $info = Db::name('flow_instance')->where(['id' => $ids[$i]])->find();
            $schemeId = 2;
            $flowTmp = $this->scheme->get($schemeId);
            if(isset($info['bizobjectid'])) {
                $cooperationInfo = Db::name('flow_cooperation')->where(['id' => $info['bizobjectid']])->find();
                $partner_id = isset($cooperationInfo['id'])?$cooperationInfo['id']:0;
                //查询跟踪信息
                $trackInfo = Db::name('flow_track')->where(['partner_id' => $partner_id])->where('year',$year)->find();
                //判断合作信息存在，节点信息不存在
                if(isset($cooperationInfo) && !empty($cooperationInfo) && empty($trackInfo)) {
                    //增加节点流程
                    $row = [
                        'instancecode' => $this->getnumber($flowTmp['flowcode']),
                        'partner_id'   => $cooperationInfo['id'],
                        'scansion'     => $cooperationInfo['scansion'],
                        'year'         => $year,
                        'that_year'    => '',
                        'next_step'    => '',
                        'other'        => '',
                        'createtime'   => time(),
                        'updatetime'   => time(),
                    ];
                    $this->flow = new FlowEngine('track',$info['originator']);
                    $this->flow->start($row);
                    //$this->success();
                }
            }
        }
        //  return $this->view->fetch();
        return json(1);
    }

    /**
     * 获取流水号
     */
    public function getnumber($code)
    {
        $row = $this->number->where(['code' => $code])->find();
        if (!$row) {
            return time();
        }
        $serial_no = '';
        $serial_no .= $row['pre'];
        if ($row['year'] == 'Y') {
            $serial_no .= Date('Y');
        }
        if ($row['month'] == 'Y') {
            $serial_no .= Date('m');
        }
        $serial_no .= str_pad($row['index'], $row['lengh'], "0", STR_PAD_LEFT);
        $row->allowField(true)->save(['index' => ($row['index'] + 1)]);
        return $serial_no;
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $delIds = [];
            $delIds = explode(',', $ids);
            $delIds = array_unique($delIds);
            $bizobjectids = Db::name('view_flow_instance')->where(['scheme' => 1])->where('id', 'in', $delIds)->column('bizobjectid');
            $bizobjectIds = array_unique($bizobjectids);
            $this->instance->where(['scheme' => 1])->where('id', 'in', $delIds)->delete();
            $this->task->where('instanceid', 'in', $delIds)->delete();
            $count = $this->cooperation->where('id', 'in', $bizobjectIds)->delete();
            if ($count) {
                $this->success();
            }
        }
    }
}
